import { Request, Response } from 'express'
import moment from 'moment'
import { GameService } from '../../services/game/GameService'
import { logger } from '../../utils/logger'

export class GameController {
  private gameService: GameService

  constructor() {
    this.gameService = GameService.getInstance()
  }

  // 创建游戏
  public createGame = async (req: Request, res: Response) => {
    try {
      const { roomId, gameType, config } = req.body
      const creator = req.user.id

      const game = await this.gameService.createGame({
        roomId,
        gameType,
        creator,
        config,
      })

      res.json({
        code: 0,
        message: '创建成功',
        data: game,
      })
    } catch (error) {
      logger.error('创建游戏失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 下注
  public placeBet = async (req: Request, res: Response) => {
    try {
      const { gameId, amount, target } = req.body
      const userId = req.user.id

      const result = await this.gameService.placeBet({
        gameId,
        userId,
        amount,
        target,
      })

      res.json({
        code: 0,
        message: '下注成功',
        data: result,
      })
    } catch (error) {
      logger.error('下注失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 获取游戏列表
  public getGames = async (req: Request, res: Response) => {
    try {
      const { roomId, status, page = 1, size = 20 } = req.query

      const games = await this.gameService.getGames({
        roomId: roomId as string,
        status: status as string,
        page: Number(page),
        size: Number(size),
      })

      res.json({
        code: 0,
        message: '获取成功',
        data: games,
      })
    } catch (error) {
      logger.error('获取游戏列表失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 获取游戏详情
  public getGameById = async (req: Request, res: Response) => {
    try {
      const { gameId } = req.params

      const game = await this.gameService.getGameById(gameId)

      res.json({
        code: 0,
        message: '获取成功',
        data: game,
      })
    } catch (error) {
      logger.error('获取游戏详情失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 获取游戏结果
  public getGameResult = async (req: Request, res: Response) => {
    try {
      const { gameId } = req.params
      const userId = req.user.id

      const result = await this.gameService.getGameResult(gameId, userId)

      res.json({
        code: 0,
        message: '获取成功',
        data: {
          ...result,
          time: moment(result.time).format('YYYY-MM-DD HH:mm:ss'),
        },
      })
    } catch (error) {
      logger.error('获取游戏结果失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 获取游戏记录
  public getGameRecords = async (req: Request, res: Response) => {
    try {
      const {
        startDate = moment().format('YYYY-MM-DD'),
        endDate = moment().format('YYYY-MM-DD'),
        type,
        page = 1,
        size = 20,
      } = req.query

      const userId = req.user.id

      const records = await this.gameService.getGameRecords({
        userId,
        startDate: startDate as string,
        endDate: endDate as string,
        type: type as string,
        page: Number(page),
        size: Number(size),
      })

      res.json({
        code: 0,
        message: '获取成功',
        data: {
          ...records,
          list: records.list.map((record) => ({
            ...record,
            time: moment(record.time).format('YYYY-MM-DD HH:mm:ss'),
          })),
        },
      })
    } catch (error) {
      logger.error('获取游戏记录失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 获取游戏统计
  public getGameStats = async (req: Request, res: Response) => {
    try {
      const { startDate = moment().format('YYYY-MM-DD'), endDate = moment().format('YYYY-MM-DD') } =
        req.query

      const userId = req.user.id

      const stats = await this.gameService.getGameStatistics({
        userId,
        startDate: startDate as string,
        endDate: endDate as string,
      })

      res.json({
        code: 0,
        message: '获取成功',
        data: {
          ...stats,
          totalAmount: Number(stats.totalAmount).toFixed(2), // 格式化金额
          winAmount: Number(stats.winAmount).toFixed(2),
          winRate: `${(stats.winRate * 100).toFixed(2)}%`,
        },
      })
    } catch (error) {
      logger.error('获取游戏统计失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }

  // 获取排行榜
  public getGameRankings = async (req: Request, res: Response) => {
    try {
      const { type = 'daily' } = req.query

      const rankings = await this.gameService.getGameRankings(type as string)

      res.json({
        code: 0,
        message: '获取成功',
        data: rankings.map((rank) => ({
          ...rank,
          amount: Number(rank.amount).toFixed(2),
          nickname: rank.nickname || '玩家***', // 昵称脱敏
        })),
      })
    } catch (error) {
      logger.error('获取排行榜失败:', error)
      res.status(500).json({
        code: 500,
        message: error.message || '服务器错误',
      })
    }
  }
}
